<template>
  <div id="FormDialog">
    <PeopleSelect
      ref="peopleSelect"
      :type="'multiple'"
      :isCheck="true"
      :open="peopleOpen"
      @cancel="peopleOpen = false"
      @submit="submitPeople"
    ></PeopleSelect>

    <DepartmentDialog
      ref="peopleSelect"
      :type="'multiple'"
      :isCheck="true"
      :open="peopleOpen1"
      @cancel="peopleOpen1 = false"
    ></DepartmentDialog>
<!--    @submit="submitPeople1"-->
    <el-row>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne">
          <div class="always_hander"></div>
          <div class="always_title">
            {{ title ? `${title}` : "工器具管理" }}
          </div>
        </div>
      </el-col>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne1">
          <el-collapse  v-model="activeNames">
<!--            <el-collapse-item name="2">-->
<!--              <template slot="title">-->
<!--                <div class="always_title1">-->
<!--                  <div></div>-->
<!--                  两列基本信息-->
<!--                </div>-->
<!--              </template>-->
              <!-- <el-card class="card-item" shadow="always"> -->
                <!-- <h3 style="font-weight: bold; font-size: 15px">{{ title }}</h3> -->
                <el-form
                  :model="formData"
                  ref="vForm"
                  :rules="rules"
                  label-position="center"
                  label-width="120px"
                  :size="medium"
                  class="el_formContent"
                >
                  <el-row>
                    <el-col :span="24" class="el_col">
                      <el-form-item
                        label="查评事件"
                        prop="reviewEvents"
                        class="required"
                        style="width: 95%"
                      >
                        <el-select
                          v-model="formData.reviewEvents"
                          class="full-width-input"
                          clearable
                          :size="medium"
                          :placeholder="placeholder"
                          :disabled="reviewEventsDisabled"
                          @change="dataChange"
                        >
                          <el-option
                            v-for="(item, index) in EventsOptions"
                            :key="index"
                            :label="item.label"
                            :value="{value: item.value, label: item.label}"
                            :disabled="item.disabled"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24" class="el_col">
                      <el-form-item label="小组名称" prop="groupName" style="width: 95%">
                        <el-input
                          v-model="formData.groupName"
                          type="text"
                          clearable
                          :size="medium"
                          :placeholder="placeholder"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24" class="el_col">
                      <el-form-item label="查评要素" prop="evaluationElements" style="width: 95%">
                        <el-input
                          v-model="formData.evaluationElements"
                          class="full-width-input"
                          clearable
                          :size="medium"
                          :disabled="taskDisabled"
                          :placeholder="placeholder1"
                          @focus="consoleHandle"
                        >
<!--                          <el-option-->
<!--                            v-for="(item, index) in SORTOptions"-->
<!--                            :key="index"-->
<!--                            :label="item.label"-->
<!--                            :value="item.value"-->
<!--                            :disabled="item.disabled"-->
<!--                          ></el-option>-->
                        </el-input>
                      </el-form-item>
                      </el-col>
                    <el-col :span="24" class="el_col">
                      <el-form-item label="组长" prop="groupLeader" style="width: 95%">
                        <el-input
                          v-model="formData.groupLeader"
                          @click.native="open"
                          type="text"
                          clearable
                          :size="medium"
                          :placeholder="placeholder"
                        ></el-input>
                      </el-form-item>
                     </el-col>
                    <el-col :span="24" class="el_col">
                      <el-form-item label="成员" prop="member" style="width: 95%">
                        <el-input
                          v-model="formData.member"
                          @click.native="open1"
                          type="text"
                          clearable
                          :size="medium"
                          :placeholder="placeholder"
                        ></el-input>
                      </el-form-item>
                     </el-col>
                    <el-col :span="24" class="el_col">
                      <el-form-item label="创建日期"  prop="creationDate"   style="width: 95%">
                        <el-date-picker
                          v-model="formData.creationDate"
                          type="date"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          clearable
                          :size="medium"
                        ></el-date-picker>
                      </el-form-item>
                      </el-col>
                  </el-row>
                </el-form>
              <!-- </el-card> -->
<!--            </el-collapse-item>-->
          </el-collapse>
        </div>
      </el-col>
      <el-dialog
        :title="titles"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
        <com-tree @rowClick="rowClick" @dialogCancel="dialogQx" @dialogTrue="dialogQr" :menuList="menuList"></com-tree>
      </el-dialog>

      <el-col :span="24" class="margin_col">
        <div class="always_handerOne1">
          <custom-buttons
            @back="handleBack"
            @confirm="handleConfirm"
          ></custom-buttons>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {listGroping,getGroping,addGroping,updateGroping,delGroping} from "../../../api/system/review/groping.js";
import {
  listBasis,
  getBasis,
  delBasis,
  listBasisAll,
  addBasis,
  updateBasis, listBasisByIdsAll,
} from "../../../api/system/review/basis";
import ComTree from "@/components/ComTree/index.vue";
import CustomButtons from "@/components/CustomButton/CustomButton.vue";
import PeopleSelect from "../../../components/Selection/index.vue";
import DepartmentDialog from "../../../components/DepartmentDialog/index.vue";
import {listEvent} from "@/api/system/review/event";
export default {
  components: {
    CustomButtons,
    PeopleSelect,
    DepartmentDialog,
    ComTree},
  props: {},
  data() {
    return {
      titles:'选择查评要素',
      dialogVisible: false,
      // placeholder提示内容
      placeholder: "请输入内容",
      placeholder1: "请选择内容",
      placeholder2: "请选择时间",
      //输入框的大小
      medium:"medium",
      activeNames: ['1', '2', '3'] ,
      fileList: [],
      tableData: [],
      menuList: [],
      formData: {},
      title: "",
      reviewSetIds: "",
      reviewSetNames: "",
      reviewStandardScore: "",
      reviewEventsDisabled: false,
      taskDisabled: false,
      rules: {
        ID: [{ required: true, message: "主键id不能为空", trigger: "blur" }],
        refId: [{ required: true, message: "外键不能为空", trigger: "blur" }],
        projectId: [
          { required: true, message: "项目id不能为空", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        sort: [{ required: true, message: "类别不能为空", trigger: "blur" }],
        groupName: [
          { required: true, message: "小组名称不能为空", trigger: "blur" },
        ],
        toolName: [
          { required: true, message: "器具名称不能为空", trigger: "blur" },
        ],
        kindNumber: [
          { required: true, message: "种类序列号不能为空", trigger: "blur" },
        ],
        type: [{ required: true, message: "型号不能为空", trigger: "change" }],
        factory: [
          { required: true, message: "制造厂家不能为空", trigger: "blur" },
        ],
        custodyPerson: [
          { required: true, message: "保管负责人不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" },
        ],
        managePerson: [
          { required: true, message: "管理责任人不能为空", trigger: "blur" },
        ],
        RESULTS: [
          { required: true, message: "检验结果不能为空", trigger: "blur" },
        ],
        inspectDate: [
          { required: true, message: "检验日期不能为空", trigger: "blur" },
        ],
        nextInspectDate: [
          { required: true, message: "下次检验日期不能为空", trigger: "blur" },
        ],
        REMARK: [{ required: true, message: "备注不能为空", trigger: "blur" }],
        FILE: [
          { required: true, message: "附件信息不能为空", trigger: "blur" },
        ],
      },
      EventsOptions: [{
      }],
      SORTOptions: [
        {
          label: "任务分配",
          value: "任务分配",
        },
        {
          label: "电力安全工器具",
          value: "电力安全工器具",
        },
        {
          label: "个人安全防护用品",
          value: "个人安全防护用品",
        },
        {
          label: "仪器仪表",
          value: "仪器仪表",
        },
      ],
      peopleOpen: false,
      peopleOpen1: false,
      FILEFileList: [],
      FILEUploadHeaders: {},
      FILEUploadData: {},
    };
  },
  computed: {},
  watch: {},
  distinguish: "",
  created() {
    this.getTitle();
    this.handleUpdate();
    this.querListEvent();
    this.formData.creationDate = new Date();
    this.formData.groupLeader = this.$store.state.user.name;
    //console.log(this.$store.state.user)
    if (this.$route.query.flowId == 1){
        this.reviewEventsDisabled = true;
        this.taskDisabled = true;
    }
  },
  mounted() {},
  methods: {
    getTitle() {
      const { ID, title } = this.$route.query;
      //console.log(ID, title);
      this.title = title;
    },
    handleBack() {
      //console.log("Back button clicked!");
      window.history.back();
      // 执行返回逻辑
    },
    /** 查询查评事件 */
    querListEvent(){
      let data = {
        "validStatus" : "有效"
      }
      listEvent(data).then((response) => {
        this.EventsOptions = [];
        response.rows.forEach((item) =>{
          this.EventsOptions.push({
            "label": item.eventTitle,
            "value": item.id
          })
        })
      });
    },
    dataChange(event){
      //console.log(event);
      this.formData.reviewEvents = event.label;
      this.formData.reviewEventsId = event.value;
        let data = {
          "ID" : this.formData.reviewEventsId
        }
        listEvent(data).then((response) => {
          //console.log(response.rows[0].reviewContentSetId);
          listBasisByIdsAll(response.rows[0].reviewContentSetId).then((res) => {
            this.menuList = this.handleTree(res, "id");
            //console.log(this.menuList);
          })
        });
    },
    rowClick(row) {
      let data = {
        "parentId" : row.id,
      }
      listBasis(data).then((res) =>{
        this.menuList = this.handleTree(res, "id");
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    consoleHandle(){
      this.dialogVisible = true;
    },
    dialogQx() {
      this.dialogVisible = false
    },
    dialogQr(val) {
      console.log(val)
      this.reviewSetIds = '';
      this.reviewSetNames = '';
      this.reviewStandardScore = '';
      this.recursiveQuery(val);
      this.formData.evaluationElementsId = this.reviewSetIds.substring(0,this.reviewSetIds.length -1);
      this.formData.evaluationElements = this.reviewSetNames.substring(0,this.reviewSetNames.length -1);
      this.formData.standardScore = this.reviewStandardScore.substring(0,this.reviewStandardScore.length -1);
      console.log(this.formData)
      if (val.length !== 0) this.dialogVisible = false
      // for (let i = 0; i < val.length; i++) {
      //   console.log(val[i])
      //   if (val[i].children.length != 0) {
      //     let row = val[i].children;
      //     let por = true;
      //     this.formData.evaluationElements += val[i].reviewProject + ',';
      //     this.formData.evaluationElementsId += val[i].id + ',';
      //     //无限循环
      //     for (let j = 1; j > 0; j++) {
      //       //循环子数据
      //       for (let k = 0; k < row.length; k++) {
      //         //判断子数据是否存在子级
      //        if (row[k].children != undefined){
      //          // row 替换新子级数据
      //          row = row[k].children;
      //          por = true;
      //          this.formData.evaluationElements += row[k].reviewProject + ',';
      //          this.formData.evaluationElementsId += row[k].id + ',';
      //        }else {
      //          this.formData.evaluationElements += row[k].reviewProject + ',';
      //          this.formData.evaluationElementsId += row[k].id + ',';
      //          por = false;
      //        }
      //       }
      //       //不存在子级数据跳出循环
      //       if (por == false){
      //         j = -1;
      //       }
      //     }
      //   }else {
      //     this.formData.evaluationElements += val[i].reviewProject + ',';
      //     this.formData.evaluationElementsId += val[i].id + ',';
      //   }
      // }

    },
    recursiveQuery(arr){
      let result = null;
      for(const item of arr){
        if(item.children != null && item.children != undefined){
          if (item.children && item.children.length > 0) {
            for(let s=0;s<item.children.length;s++){
              this.reviewSetIds += item.children[s].id + ","
              this.reviewSetNames += item.children[s].reviewProject + ","
              this.reviewStandardScore += item.children[s].reviewStandardScore + ","
            }
            result = this.recursiveQuery(item.children);
          }else {
            this.reviewSetIds += item.id + ","
            this.reviewSetNames += item.reviewProject + ","
            this.reviewStandardScore += item.reviewStandardScore + ","
          }
        }
      }
    },
    handleConfirm() {
      this.$refs["vForm"].validate((valid) => {
        if (valid) {
          // this.buttonLoading = true;
          if (this.formData.id !== undefined) {
            updateGroping(this.formData)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
              })
              .finally(() => {
                this.$router.push("/review/reviewPrepare/evaluationGrouping");
                // this.buttonLoading = false
                this.$refs.formData.resetFields(); // 重置表单数据
                this.reset();
              });
          } else {
            addGroping(this.formData)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
              })
              .finally(() => {
                // this.buttonLoading = false;
                this.$refs.vForm.resetFields(); // 重置表单数据
                this.$router.push("/review/reviewPrepare/evaluationGrouping");
                this.reset();
              });
          }
        }
      });
    },
    reset() {
      this.formData = {
        id: undefined,
        reviewEvents: undefined,   //查评事件
        groupName: undefined,   //小组名称
        groupLeader: undefined,    //小组组长
        groupLeaderCode: undefined,   //组长编号
        member: undefined,    //成员
        memberCode: undefined,   //成员编号
        creationDate: undefined,   //创建时间
        isDelete: undefined,    //是否删除
        taskAllocation: undefined,    //任务分配
        evaluationElements: '',    //查评要素
        standardScore: undefined,    //标准分
        reviewStatus: undefined,    //评审状态
        reviewEventsId: undefined,    //查评事件id
        evaluationElementsId: '',    //查评事件id
      };
    },
    submitForm() {},
    handleUpdate() {
      const { ID } = this.$route.query;
      this.reset();
      if (this.$route.query.flowId == 1) {
        getGroping(ID).then((response) => {
          console.log(response.data);
          this.loading = false;
          this.formData = response.data;
        });
      }
    },
    resetForm() {
      this.$refs["vForm"].resetFields();
    },
    handleSuccess(response, file, fileList) {
      // 文件上传成功后，将文件信息添加到表格数据中
      this.fileList = fileList;
      this.tableData.push({
        name: file.name,
        size: (file.size / 1024).toFixed(2) + "KB",
        url: URL.createObjectURL(file.raw),
      });
    },
    handlePreview(file) {
      console.log("预览文件：", file);
    },
    handleRemove(file, fileList) {
      // 文件删除时，同时从表格数据中删除对应的文件信息
      this.fileList = fileList;
      this.tableData = this.tableData.filter((item) => item.name !== file.name);
    },
    beforeRemove(file, fileList) {
      console.log(file)
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // open() {
    //   console.log('ddddd')
    //   this.distinguish = "1";
    //   this.peopleOpen = false;
    // },
    open1() {
      this.distinguish = "2";
      this.peopleOpen = true;
    },
    submitPeople(peopleList) {
      if (this.distinguish == "1"){
        if (peopleList.length != 1){
          return this.$message.warning('请选择一位人员');
        }
        this.formData.groupLeader = peopleList[0].userName;
      }else if (this.distinguish == "2"){
        var atat = "";
        for (let i = 0; i < peopleList.length; i++) {
            atat += peopleList[i].userName + ",";
        }
        atat =  atat.substring(0, atat.length - 1);
        this.formData.member = atat;
      }
      this.peopleOpen = false;
    },
    beforeRemoves(row) {
      console.log(this.fileList)
      this.$confirm(`确定移除 ${row.name}？`).then(() => {
      // 确认删除后的逻辑，你可以在这里调用 handleRemove 方法或其他自定义逻辑
      this.handleRemove(row, this.fileList);
    }).catch(() => {
      // 取消删除的逻辑
    });
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传不超过3个文件");
    },
  },
};
</script>

<style lang="scss" scoped>
.el_col {
  display: flex;
  justify-content: space-evenly;
  align-content: center;
}
.card-container {
  height: 80%; /* 设置容器的高度为 100% */
  display: flex;
  flex-direction: column;
}
.card-item {
  flex: 1; /* 平分容器的宽度 */
}
#FormDialog {
  height: 100%;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
}
.dialog-footer1 {
  width: 100%;
  height: 6vh;
  background: #ffffff;
  text-align: center;
  line-height: 6vh;
}
.el-card {
  margin-top: 10px;
}
.el-select {
  width: 100%;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.el-form-item {
  width: 30%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.el-form-item {
  margin-bottom: 11px;
}
.el-table {
  min-height: 50% !important;
}
.always_handerOne {
  height: 80px;
  background-color: #ffffff;
  // border-radius: 14px;
}
.always_handerOne1 {
  height: auto;
  background-color: #ffffff;
  // border-radius: 14px;
  padding: 20px;
}
.always_title {
  font-size: 20px;
  font-weight: bold;
  line-height: 53px;
  margin-left: 45%;
}
.always_title1 {
  font-size: 18px;
  font-weight: bold;
  // line-height: 53px;
  margin-left: 15px;
  position: relative;
}
.always_title1 ::before {
  content: "|";
  flex-shrink: 0;
  width: 4px;
  height: 6%;
  margin-left: 12px;
  // background: #f90;
  color: #f90;
  position: absolute;
  left: -22px;
  margin-bottom: 12px;
}
.always_hander {
  background: url(../../../assets/images/header0.png);
  height: 20px;
  width: 100%;
}
// .margin_col {
//   margin-bottom: 20px;
// }
.el_formContent  .el-form-item{
  width: 50%;
  margin-bottom: 17px;
}
.text-box-container{
  text-align: left;
}
</style>
